const { createClient } = require("redis");
const { v4: uuidv4 } = require("uuid");
const config = require("../../config");

class Execution {
    constructor() {
        this.redisUrl = `redis://:${config.redis.password}@${config.redis.host}:${config.redis.port}/${config.redis.db}`;
    }

    /**
     * 
     * @param {string} machineUuid 
     * @param {{testPlanName: string, jmxFilePath: string, initialThreadNumber: number, threadNumberIncrement: number}[]} testPlans 
     * @param {number} duration 
     * @param {number} maxRound 
     * @returns {Promise<string>}
     */
    async set(machineUuid, testPlans, duration, maxRound) {
        const executionUuid = uuidv4();
        const key = `execution:${machineUuid}`;
        const value = JSON.stringify({ method: "execute", parameter: { uuid: executionUuid, testPlans, duration, maxRound } });
        const redisClient = createClient({ url: this.redisUrl });
        await redisClient.connect();
        await redisClient.set(key, value);
        await redisClient.disconnect();
        return executionUuid;
    }

    async get(machineUuid) {
        const redisClient = createClient({ url: this.redisUrl });
        redisClient.connect();
        const key = `execution:${machineUuid}`;
        let value = await redisClient.get(key);
        await redisClient.del(key);
        redisClient.disconnect();
        return JSON.parse(value);
    }

}

module.exports = Execution;